package utils

import (
	"bytes"

	"github.com/dhowden/tag"
)

type AutioTagInfo struct {
	Title       string `json:"title"`
	Artist      string `json:"artist"`
	Album       string `json:"album"`
	Year        int    `json:"year"`
	Vendor      string `json:"vendor"`
	FileType    string `json:"file_type"`
	PictrueData []byte `json:"pictrue_data"`
	PictrueExc  string `json:"pictrue_exc"`
}

func newAutioTagInfo() *AutioTagInfo {
	return &AutioTagInfo{}
}

// 读取解析此音乐文件内的标签数据
func (AutioTagInfo) AutioTagRead(fileByte []byte, fileSize int64, desc string) (*AutioTagInfo, error) {
	file := bytes.NewReader(fileByte)
	fileInfo, err := tag.ReadFrom(file)
	if err != nil {
		return nil, err
	}

	title := fileInfo.Title()
	var album string
	var vendor string
	for k, v := range fileInfo.Raw() {
		switch k {
		case "vendor":
			vendor, _ = v.(string)
		case "title":
			title, _ = v.(string)
		case "album":
			album, _ = v.(string)
		}
	}

	picture := fileInfo.Picture()
	var data []byte
	var exc string
	if picture == nil {
		data = []byte{}
		exc = ""
	} else {
		data = picture.Data
		exc = picture.Ext
	}
	auto := &AutioTagInfo{
		Title:       title,
		Artist:      fileInfo.Artist(),
		Album:       album,
		Year:        fileInfo.Year(),
		Vendor:      vendor,
		FileType:    string(fileInfo.FileType()),
		PictrueData: data,
		PictrueExc:  exc,
	}
	return auto, nil
}
